/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.afd.ozblip.activity;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import android.content.Intent;
import android.content.res.Configuration;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;

import com.afd.ozblip.app.CommonInfo;
import com.afd.ozblip.chat.ChatClient;
import com.afd.ozblip.entity.UserEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.util.SharedUtil;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;

/**
 * This demo shows how GMS Location can be used to check for changes to the users location. The "My Location"
 * button uses GMS Location to set the blue dot representing the users location. To track changes to the users
 * location on the map, we request updates from the {@link LocationClient}.
 */
public class WelcomeActivity extends BaseActivity implements ConnectionCallbacks, OnConnectionFailedListener,
		LocationListener, OnMyLocationButtonClickListener
{
	
	private LocationClient mLocationClient;
	
	// These settings are the same as the settings for the map. They will in
	// fact give you updates
	// at the maximal rates currently possible.
	private static final LocationRequest REQUEST = LocationRequest.create().setInterval(5000) // 5 seconds
			.setFastestInterval(16) // 16ms = 60fps
			.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome);
		// 获取当前设置的语言环境
		getCurrentLocale();
		// 获取用户登录后信息
		getLoginedUserInfo();
		new Handler().postDelayed(new Runnable()
		{
			public void run()
			{
				Intent indexIntent = new Intent(WelcomeActivity.this, IndexActivity.class);
				startActivity(indexIntent);
				finish();
			}
		}, 1000);
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		setUpLocationClientIfNeeded();
		mLocationClient.connect();
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
		if (mLocationClient != null)
		{
			mLocationClient.disconnect();
		}
	}
	
	private void getLoginedUserInfo()
	{
		UserEntity userInfo = SharedUtil.fetchUserInfo(this);
		if (userInfo != null)
		{
			isLogin = true;
			commonUserInfo = userInfo;
			CommonInfo.isLogin = isLogin;
			CommonInfo.commonUserInfo = commonUserInfo;
			// 并访问登录接口
			requestLoginInfo();
		}
	}
	
	/**
	 * 用户注册数据提交
	 * 
	 * @param paramString
	 */
	public void requestLoginInfo()
	{
		AsyncLoadData ald = new AsyncLoadData(mContext, "", new AsyncAction()
		{
			@Override
			public void doLoad() throws Exception
			{
				// 读取原来登录成功的邮箱和密码
				String[] result = SharedUtil.fetchLoginInfo2(mContext);
				// 获取提交参数
				Map<String, Object> registerParamMap = new HashMap<String, Object>();
				registerParamMap.put("userName", result[0]);
				// passwordStr =
				// StringUtil.getMD5Str(passwordStr);服务器已MD5加密
				registerParamMap.put("passWord", result[1]);
				// 发送请求
				byte[] bUserRegiter = HttpUtil.requestByPost(mContext, Constants.USER_LOGIN_API, registerParamMap);
				if (bUserRegiter != null)
				{
					commonUserInfo = new ParseJson().parseUserInfoJson(bUserRegiter);
				}
			}
			
			@Override
			public void loadEnd() throws Exception
			{
				if (commonUserInfo != null)
				{
					boolean loginFlg = commonUserInfo.getLogintResult();
					if (loginFlg)
					{
						isLogin = true;
						CommonInfo.isLogin = isLogin;
						CommonInfo.commonUserInfo = commonUserInfo;
						// 开起chat对话连接
						new Thread(new Runnable()
						{
							public void run()
							{
								ChatClient.getInstances(commonUserInfo.getUserId());
							}
						}).start();
						// 读取原来登录成功的邮箱和密码
						String[] result = SharedUtil.fetchLoginInfo2(mContext);
						// 存储用户信息，方便下一次登录
						SharedUtil.storeLoginInfo(mContext, result[0], result[1], commonUserInfo);
					}
					else
					{
						loginFailed();
					}
				}
				else
				{
					loginFailed();
				}
			}
			
		});
		ald.execute(0);
	}
	
	private void loginFailed()
	{
		isLogin = false;
		CommonInfo.isLogin = isLogin;
	}
	
	private void setUpLocationClientIfNeeded()
	{
		if (mLocationClient == null)
		{
			mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
					this); // OnConnectionFailedListener
		}
	}
	
	/**
	 * Button to get current Location. This demonstrates how to get the current Location as required without
	 * needing to register a LocationListener.
	 */
	public void showMyLocation(View view)
	{
		if (mLocationClient != null && mLocationClient.isConnected())
		{
			String msg = "Location = " + mLocationClient.getLastLocation();
			Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
		}
	}
	
	/**
	 * Implementation of {@link LocationListener}.
	 */
	@Override
	public void onLocationChanged(Location location)
	{
		System.out.println(location);
	}
	
	/**
	 * Callback called when connected to GCore. Implementation of {@link ConnectionCallbacks}.
	 */
	@Override
	public void onConnected(Bundle connectionHint)
	{
		commonLocation = mLocationClient.getLastLocation();
		new Handler().postDelayed(new Runnable()
		{
			public void run()
			{
				Intent indexIntent = new Intent(WelcomeActivity.this, IndexActivity.class);
				startActivity(indexIntent);
				finish();
			}
		}, 3000);
		// mLocationClient.requestLocationUpdates(REQUEST, this); //
		// LocationListener
	}
	
	/**
	 * Callback called when disconnected from GCore. Implementation of {@link ConnectionCallbacks}.
	 */
	@Override
	public void onDisconnected()
	{
		// Do nothing
	}
	
	/**
	 * Implementation of {@link OnConnectionFailedListener}.
	 */
	@Override
	public void onConnectionFailed(ConnectionResult result)
	{
		// Do nothing
	}
	
	@Override
	public boolean onMyLocationButtonClick()
	{
		Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
		// Return false so that we don't consume the event and the default
		// behavior still occurs
		// (the camera animates to the user's current position).
		return false;
	}
	
	private void getCurrentLocale()
	{
		String languageToLoad = SharedUtil.fetchLanguageInfo(this);
		Locale locale = new Locale(languageToLoad);
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		getBaseContext().getResources().updateConfiguration(config, null);
	}
}
